package edu.ccut.saturn.basecomponent.database.facade;

import java.sql.Connection;

import edu.ccut.saturn.basecomponent.database.ISaturnSQL;
import edu.ccut.saturn.basecomponent.database.ISaturnSQLBuilder;
import edu.ccut.saturn.basecomponent.database.IUpdateSQLBuilder;
import edu.ccut.saturn.basecomponent.database.SaturnSQLBuilderFactory;
import edu.ccut.saturn.basecomponent.database.SaturnSQLHandler;
import edu.ccut.saturn.basecomponent.database.util.SaturnDataUtil;
import edu.ccut.saturn.component.SaturnData;

public class UpdateByCondition {
	public int execute(SaturnData saturnData, String condition,
			String specialcolumn, Connection conn) throws Exception {
		String dbType = SaturnDataUtil.getStandardDBType(saturnData);
		ISaturnSQLBuilder builder = SaturnSQLBuilderFactory
				.getSaturnSQLBuilder(dbType);
		if(condition!=null){
			condition = ""
				+ condition;
		}else{
			condition = " WHERE 1=1 ";
		}
		if (builder != null) {
			IUpdateSQLBuilder sqlBuilder = builder
					.getUpdateSQLBuilder(getBuilderType(saturnData));
			ISaturnSQL saturnSQL = sqlBuilder.build(saturnData, condition,
					specialcolumn);
			int count = SaturnSQLHandler.executeUpdate(saturnSQL,conn);
			return count;
		}
		return 0;
	}

	private String getBuilderType(SaturnData saturnData) {
		// 如果有大数据
		if (SaturnDataUtil.hasLOB(saturnData)) {
			return ISaturnSQL.UPDATE_LOB_OPERATION;
		} else {
			return ISaturnSQL.UPDATE_OPERATION;
		}
	}

//	private boolean hasLOB(SaturnData saturnData) {
//		IDataInfo dataInfo = saturnData.getSaturnDataInfo();
//		for (String key : dataInfo.keySet()) {
//			IDataItem dataItem = dataInfo.getDataItem(key);
//			if (OracleAttribute.isLOB(dataItem.getType())) {
//				if (saturnData.get(key) != null) {
//					return true;
//				}
//			}
//		}
//		return false;
//	}

}
